<template>
	<view
		class="diy-image-bd"
		:style="'width:' + width + '; height:' + height + ';'"
	>
		<image
			:style="
				(width ? 'width:' + width + ';' : '') +
				' ' +
				(height ? 'height:' + height + ';' : '') +
				' ' +
				(style ? style : '')
			"
			mode="aspectFill"
			:src="imgIsTrue ? src : ''"
			@click="previewImage()"
		></image>
		<view
			v-if="!imgIsTrue"
			class="diy-image-error"
			:style="style ? style : ''"
		>
			<uni-icons type="image" color="#969799" size="80rpx"></uni-icons>
		</view>
	</view>
</template>

<script>
export default {
	name: 'DiyImage',
	props: {
		isGetImage: {
			type: Boolean,
			default: true,
		},
		src: {
			type: String,
			value: '',
		},
		previewSrcList: {
			type: Array,
			value: [],
		},
		initialIndex: {
			type: [String, Number],
			default: 0,
		},
		width: {
			type: String,
			value: '',
			default: '160rpx',
		},
		height: {
			type: String,
			value: '',
			default: '160rpx',
		},
		style: {
			type: String,
			value: '',
		},
		fit: {
			type: String,
			value: '',
		},
	},
	data() {
		return {
			imgIsTrue: false,
			preHeight: 0,
		}
	},
	methods: {
		getIsTrueImage() {
			let _that = this
			uni.getImageInfo({
				src: this.src,
				success: function (image) {
					console.log(image)
					console.log('存在')
					_that.imgIsTrue = true
				},
				fail: function (image) {
					console.log(image)
					console.log('不存在')
					_that.imgIsTrue = false
				},
			})
		},
		change(e) {
			console.log('当前模式：' + e.type + ',状态：' + e.show)
		},
		previewImage() {
			const _that = this
			// 预览图片
			uni.previewImage({
				urls: [
					...new Set([
						this.previewSrcList[this.initialIndex],
						...this.previewSrcList,
					]),
				],
				longPressActions: {
					itemList: ['发送给朋友', '保存图片', '收藏'],
					success: function (data) {
						console.log(
							'选中了第' +
								(data.tapIndex + 1) +
								'个按钮,第' +
								(data.index + 1) +
								'张图片'
						)
					},
					fail: function (err) {
						console.log(err.errMsg)
					},
				},
			})
		},
	},
	mounted() {
		if (this.isGetImage) {
			this.getIsTrueImage()
		} else {
			this.imgIsTrue = true
		}
	},
	watch: {
		src() {
			this.getIsTrueImage()
		},
	},
}
</script>

<style scoped>
.diy-image-bd {
	position: relative;
	display: inline-block;
	width: 100%;
	height: 27vw;
}

.diy-image-error {
	width: 100%;
	height: 100%;
	position: absolute;
	top: 0;
	left: 0;
	display: flex;
	-webkit-box-orient: vertical;
	-webkit-box-direction: normal;
	flex-direction: column;
	-webkit-box-align: center;
	align-items: center;
	-webkit-box-pack: center;
	justify-content: center;
	color: #969799;
	font-size: 14px;
	background-color: #f7f8fa;
}
</style>
